 package com.example.xy_assistant;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.PopupMenu;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.xy_assistant.adapter.NoteAdapter;
import com.example.xy_assistant.bean.Note;
import org.litepal.LitePal;
import java.util.List;

public class NoteActivity extends AppCompatActivity {

    private static final String TAG = "NoteActivity";
    private ListView lv_note;
    private List<Note> notes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note);
        initView();
    }

    @Override
    protected void onStart() {
        notes = LitePal.findAll(Note.class);
        NoteAdapter noteAdapter = new NoteAdapter(this, notes);
        lv_note.setAdapter(noteAdapter);

        lv_note.setOnItemClickListener((parent, view, position, id) -> {
            PopupMenu popupMenu = new PopupMenu(this, view);
            popupMenu.getMenuInflater().inflate(R.menu.menu_click,popupMenu.getMenu());
            popupMenu.show();
            popupMenu.setOnMenuItemClickListener(item -> {
                Note note = notes.get(position);
                switch (item.getItemId()){
                    case R.id.btn_update:
                        Intent intent = new Intent(NoteActivity.this, NewNoteActivity.class);
                        intent.putExtra("note",note.getId());
                        startActivity(intent);
                        break;
                    case R.id.btn_delete:
                        LitePal.delete(Note.class,note.getId());
                        notes.remove(position);
                        noteAdapter.notifyDataSetChanged();
                }
                return false;
            });

        });
        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_note, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()==R.id.menu_new){
            Intent intent = new Intent(NoteActivity.this, NewNoteActivity.class);
            startActivity(intent);
            return true;
        }else if (item.getItemId()==R.id.ment_exit){
            finish();
        }
        return false;
    }

    private void initView() {
        lv_note = (ListView) findViewById(R.id.lv_note);
    }
}